package org.mao.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.mao.controller.TestController;
import org.springframework.http.HttpHeaders;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.google.gson.Gson;

public class HivWebSocketHandler implements WebSocketHandler {

	public static Map<String, WebSocketSession> sessionMap = new HashMap<String, WebSocketSession>();

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		System.out.println("websocket connection closed......");
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		System.out.println("connect to the websocket success......");
		// session.sendMessage(new TextMessage("Server:connected OK!"));
	}

	@Override
	public void handleMessage(final WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		System.out.println(message.getPayload());
		Gson gson = new Gson();
		final ChartMessage chartMessage = gson.fromJson(message.getPayload().toString(), ChartMessage.class);
		if (TestController.nickNameSet.contains(chartMessage.getSender())) {
			final String nickName = chartMessage.getSender();
			if (!sessionMap.containsKey(nickName)) {
				sessionMap.put(nickName, session);
			}
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						TextMessage tmsg = new TextMessage(nickName + ": " + chartMessage.getMessage());
						for (Map.Entry<String, WebSocketSession> entry : sessionMap.entrySet()) {
							if (entry.getValue().isOpen()) {
								if (!entry.getKey().equals(nickName)) {
									entry.getValue().sendMessage(tmsg);
								} else {
									entry.getValue().sendMessage(new TextMessage("{{{success}}}"+ nickName + ": " + chartMessage.getMessage()));
								}
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			}).start();
		} else {
			session.sendMessage(new TextMessage("{{{unregister}}}"));
		}
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable e) throws Exception {
		if (session.isOpen()) {
			session.close();
		}
		System.out.println("websocket connection error......");
	}

	@Override
	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}

}
